local core = require "md5.core"

local function lower16(c)
    return string.format("%02x", string.byte(c))
end

local function upper16(c)
    return string.format("%02X", string.byte(c))
end

---md5码小写
function core.encodeLower(k)
    k = core.sum(k)
    return (string.gsub(k, ".", lower16))
end

---md5码大写
function core.encodeUpper(k)
    k = core.sum(k)
    return (string.gsub(k, ".", upper16))
end

local function get_ipad(c)
    return string.char(c:byte() ~ 0x36)
end

local function get_opad(c)
    return string.char(c:byte() ~ 0x5c)
end

function core.hmacmd5(data, key)
    if #key > 64 then
        key = core.sum(key)
        key = key:sub(1, 16)
    end
    local ipad_s = key:gsub(".", get_ipad) .. string.rep("6", 64 - #key)
    local opad_s = key:gsub(".", get_opad) .. string.rep("\\", 64 - #key)
    local istr = core.sum(ipad_s .. data)
    local ostr = core.encodeLower(opad_s .. istr)
    return ostr
end

return core
